import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class DioCase extends StatefulWidget {
  const DioCase({ Key? key }) : super(key: key);

  @override
  _DioCaseState createState() => _DioCaseState();
}



class _DioCaseState extends State<DioCase> {
  List _channels = [];
  // aboutToAppear
  @override
  void initState() {
    // TODO: implement initState
    // 发起请求
    getAllChannels();
    super.initState();
  }

  getAllChannels() async {
    String BASE_URL = 'https://geek.itheima.net';   //基地址
    Dio dio = Dio(); //创建请求实例对象
    // 发起请求  获取数据
   var res = await dio.get('$BASE_URL/v1_0/channels');
    setState(() {
      _channels = res.data['data']['channels'] as List;
    });// 这个函数只要执行 就会更新一遍数据
    // 渲染数据
  }
  @override
  Widget build(BuildContext context) {
    return GridView(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 4,
        mainAxisSpacing: 10,
        crossAxisSpacing: 10,
      ),
      children: _channels.map((dynamic item) {
        return Container(
          color: Colors.blue,
          alignment: Alignment.center,
          margin: const EdgeInsets.all(10),
          child: Text(
            item["name"],
            style: const TextStyle(color: Colors.white, fontSize: 20),
          ),
        );
      }).toList(),
    );
  }
}